﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using chihuopig.Web.Framework;

namespace chihuopig.Web
{
    public abstract  class WebViewController: Controller,IResultFilter
    {
        private string platformStr = "Web";

        public void OnResultExecuting(ResultExecutingContext context)
        {
            var ViewResviw = context.Result as ViewResult;
            if (ViewResviw != null)
            {
                var Controllers = context.RouteData.Values["controller"]?.ToString();
                var action = context.RouteData.Values["action"]?.ToString();
                var id = context.RouteData.Values["id"]?.ToString();
                var html = context.RouteData.Values["html"]?.ToString();
                platformStr = context.RouteData.Values["platform"].ToString();
                if (!platformStr.Contains("App"))
                {

                    if (html != null)
                    {
                        ViewResviw.ViewName = $"~/{platformStr}/Views/{Controllers}/{id}.shtml";
                    }
                    else
                    {
                        ViewResviw.ViewName = $"~/{platformStr}/Views/{Controllers}/{action}.cshtml";
                    }
                }
                else
                {
                    //Microsoft.AspNetCore.Mvc.Controller p = new Microsoft.AspNetCore.Mvc.Controller();
                    context.Result =new JsonResult(ViewResviw.Model) ;
                }
            }
        }

        public void OnResultExecuted(ResultExecutedContext context)
        {
            
        }
       
        protected PlatformType GetPlatformType
        {
            get
            {
                if (Request.Query["compileType"] == "miniprogram")
                {
                    return PlatformType.WeixinApp;
                }
                else if (Request.Headers["User-Agent"].ToString().ToLower().Contains("micromessenger"))
                {
                    return PlatformType.Weixin;
                }
                else if (platformStr == "Web")
                {
                    return PlatformType.Web;
                }
                else if (platformStr == "APP")
                {
                    return PlatformType.APP;
                }
                else
                {
                    return PlatformType.Admin;
                }
            }
        }

      


    }
}
